package com.ls.controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.ls.pojo.SysRole;
import com.ls.pojo.SysUser;
import com.ls.service.sysRole.SysRoleService;
import com.ls.service.sysUser.SysUserService;
import com.ls.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/sys/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/list")
    public String list(@RequestParam(required = false) String queryRealName,
                       @RequestParam(required = false) Integer queryRoleId, Model model,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        List<SysRole> roleList = null;
        byte pageSize = 5;

        try {
            int totalCount = this.sysUserService.getUserCount(queryRealName, queryRoleId);

            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);

            int totalPageCount = pages.getTotalPageCount();

            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
            }

            userList = this.sysUserService.getUserList(queryRealName, queryRoleId, pageIndex, Integer.valueOf(pageSize));
            model.addAttribute("userList", userList);

            roleList = this.sysRoleService.getRoleList();
            model.addAttribute("roleList", roleList);

            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", pageIndex);

            return "sysUser/list";
        } catch (Exception e) {
            e.printStackTrace();

            return "redirect:/toSysError";
        }
    }

    @GetMapping(value = "/toUpdatePwd")
    public String toUpdatePwd (HttpSession session) {
        return session.getAttribute("userSession") == null ? "redirect:/toLogin" : "sysUser/updatePassword";
    }

    @PostMapping({"/savePassword"})
    public String savePassword(@RequestParam String newPassword, HttpSession session, HttpServletRequest request) throws Exception {
        boolean flag = false;
        SysUser loginUser = (SysUser)session.getAttribute("userSession");
        if (loginUser != null && !StringUtils.isNullOrEmpty(newPassword)) {
            flag = sysUserService.updatePwd(loginUser.getId(), newPassword);
            if (flag) {
                request.setAttribute("message", "修改密码成功,请退出并使用新密码重新登录！");
                session.removeAttribute("userSession");
                return "login";
            } else {
                request.setAttribute("message", "修改密码失败！");
            }
        } else {
            request.setAttribute("message", "修改密码失败！");
        }

        return "sysUser/updatePassword";
    }

    @GetMapping(value = "/toAdd")
    public String toAdd() {
        return "sysUser/add";
    }

    @PostMapping(value = "/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(required = false) MultipartFile idPic,
                      @RequestParam(required = false) MultipartFile workPic) {
        String idPicPath = null;
        String workPicPath = null;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");

        logger.info("uploadFile path ============== > " + path);

        if (!idPic.isEmpty()) {
            String oldFileName = idPic.getOriginalFilename();
            logger.info("uploadFile oldFileName ============== > " + oldFileName);

            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.debug("uploadFile prefix============> " + prefix);

            int fileSize = 500000;
            logger.debug("uploadFile size============> " + idPic.getSize());

            if (idPic.getSize() > (long)fileSize) {
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "sysUser/add";
            }

            if (!prefix.equalsIgnoreCase("jpg") && !prefix.equalsIgnoreCase("png") &&
                    !prefix.equalsIgnoreCase("jpeg") && !prefix.equalsIgnoreCase("pneg")) {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "sysUser/add";
            }

            String fileName = System.currentTimeMillis() + (long) RandomUtils.nextInt(1000000) + "_Personal.jpg";

            logger.debug("new fileName======== " + idPic.getName());

            File targetFile = new File(path, fileName);

            if (!targetFile.exists()) {
                targetFile.mkdir();
            }

            try {
                idPic.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("uploadFileError", " * 上传失败！");
                return "sysUser/add";
            }

            idPicPath = path + File.separator + fileName;
        }

        if (!workPic.isEmpty()) {
            String oldFileName = workPic.getOriginalFilename();
            logger.info("uploadFile oldFileName ============== > " + oldFileName);

            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.debug("uploadFile prefix============> " + prefix);

            int fileSize = 500000;
            logger.debug("uploadFile size============> " + workPic.getSize());

            if (workPic.getSize() > (long)fileSize) {
                request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
                return "sysUser/add";
            }

            if (!prefix.equalsIgnoreCase("jpg") && !prefix.equalsIgnoreCase("png") && !prefix.equalsIgnoreCase("jpeg") && !prefix.equalsIgnoreCase("pneg")) {
                request.setAttribute("uploadWpError", " * 上传图片格式不正确");
                return "sysUser/add";
            }

            String fileName = System.currentTimeMillis() + (long)RandomUtils.nextInt(1000000) + "_Personal.jpg";

            logger.debug("new fileName======== " + workPic.getName());

            File targetFile = new File(path, fileName);

            if (!targetFile.exists()) {
                targetFile.mkdir();
            }

            try {
                workPic.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("uploadWpError", " * 上传失败！");
                return "sysUser/add";
            }

            workPicPath = path + File.separator + fileName;
        }

        try {
            sysUser.setCreatedUserId(((SysUser)session.getAttribute("userSession")).getId());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.add(sysUser)) {
                return "redirect:/sys/user/list";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存用户信息失败");
        }

        return "sysUser/add";
    }

    @ResponseBody
    @GetMapping(value = "/userExist")
    public String userExist(@RequestParam(required = true) String account) {
        logger.debug("验证用户名account=" + account + "的用户是否存在");
        HashMap resultMap = new HashMap();

        try {
            if (account != null && !account.trim().equals("")) {
                SysUser sysUser = sysUserService.getByAccount(account);
                if (sysUser != null) {
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } else {
                resultMap.put("exist", -1);
                resultMap.put("msg", "用户名不可以为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @PostMapping(value = "/checkOldPwd")
    public Object checkOldPwd(@RequestParam String oldPassword, HttpSession session) {
        logger.debug("验证原密码 oldPassword ===================== " + oldPassword);
        HashMap resultMap = new HashMap();

        try {
            if (null == session.getAttribute("userSession")) {
                resultMap.put("result", "sessionerror");
            } else if (StringUtils.isNullOrEmpty(oldPassword)) {
                resultMap.put("result", "error");
            } else {
                String sessionPwd = ((SysUser)session.getAttribute("userSession")).getPassword();
                if (oldPassword.equals(sessionPwd)) {
                    resultMap.put("result", "true");
                } else {
                    resultMap.put("result", "false");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/toUpdate")
    public String toUpdate(@RequestParam Integer uid, Model model) throws Exception {
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    @PostMapping(value = "/update")
    public String update(SysUser sysUser, HttpSession session) throws Exception {
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute("userSession")).getId());
        return sysUserService.update(sysUser) ? "redirect:/sys/user/list" : "sysUser/update";
    }

    @ResponseBody
    @DeleteMapping(value = "/del/{id}")
    public String del(@PathVariable Integer id) {
        HashMap resultMap = new HashMap();

        try {
            if (sysUserService.deleteById(id)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/view/{id}")
    public String view(@PathVariable Integer id, Model model) throws Exception {
        logger.debug("根据id查询用户详情" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    @ResponseBody
    @GetMapping(value = "/{id}/view")
    public Object view(@PathVariable Integer id) throws Exception {
        logger.debug("根据id查询用户详情" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        logger.debug("查询到用户信息：" + sysUser);
        return "sysUser/view";
    }
}